package com.yx.fmmall.service.impl;

import com.yx.fmmall.dao.UserDao;
import com.yx.fmmall.entity.User;
import com.yx.fmmall.service.UserService;
import com.yx.fmmall.utils.MD5Utils;
import com.yx.fmmall.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @Classname UserServiceImpl
 * @Date 2022/01/16 12:31
 * @Author by yx
 * @Description :
 */
@Service
//@Scope("singleton") // 单例,默认
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    @Transactional //事务控制
    public ResultVO userResgit(String username, String password) {
        synchronized (this) { // 锁service对象
            // 1. 根据用户查询,这个用户是否已经被注册
            User user = userDao.queryUserByName(username);
            // 2. 如果没有被注册则进行保存操作
            if (user == null) {
                String md5Password = MD5Utils.md5(password);
                user = new User();
                user.setUsername(username);
                user.setPassword(md5Password);
                user.setUserImg("img/default.png");
                user.setUserRegtime(new Date());
                user.setUserModtime(new Date());
                int i = userDao.insertUser(user);
                if (i > 0) {
                    return new ResultVO(10000, "注册成功!", null);
                } else {
                    return new ResultVO(10000, "注册失败!", null);
                }
            } else {
                return new ResultVO(10001, "该用户名已被注册", null);
            }
        }
    }

    @Override
    public ResultVO checkLogin(String username, String password) {
        User user = userDao.queryUserByName(username);
        if (user == null) {
            return new ResultVO(10001, "登录失败,用户名或密码错误", null);
        } else {
            String md5Pwd = MD5Utils.md5(password);
            if (md5Pwd.equals(user.getPassword())) {
                return new ResultVO(10000, "登录成功!", user);
            } else {
                return new ResultVO(10001, "登录失败,用户名或密码错误", null);
            }
        }
    }
}
